#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>

int main() {
	int listener;
	struct sockaddr_in addr;
	char buf[1024];
	int bytes_read;
	listener = socket(AF_INET, SOCK_DGRAM, 0);
	
	if(listener < 0)
	{
		perror("socket");
		exit(errno);
	}

	addr.sin_family = AF_INET;
	addr.sin_port = htons(3425);
	addr.sin_addr.s_addr = htonl(INADDR_ANY);

	if(bind(listener, (struct sockaddr *)&addr, sizeof(addr)) < 0)
	{
		perror("bind");
		exit(errno);
	}

	while (1) {
		struct sockaddr_in client_address;
		int client_address_len = sizeof(struct sockaddr_in);
		
		bytes_read = recvfrom(listener, buf, 1024, 0, (struct sockaddr *) &client_address, &client_address_len);
		if(bytes_read <= 0) break ;

		buf[bytes_read] = '\0';

		printf("echo to %s:%d\t msg: %s\n", (char*)inet_ntoa(client_address.sin_addr), ntohs(client_address.sin_port), buf);
		sendto(listener, buf, bytes_read, 0, (struct sockaddr *)&client_address, client_address_len);
	}
	
	close(listener);
	
	return 0;
}

